package game.io;

import game.model.MapFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;

public class MapLoader {

	private MapFactory mapFactory;
	
	public MapLoader() {
		this.mapFactory = new MapFactory();
	}
	
	public void load( String mapName ) {
		URL url = getClass().getResource( "resources/maps/" + mapName + ".map" );
		File mapDir;
		try {
			mapDir = new File( url.toURI() );
			for( File propertieFile : mapDir.listFiles() ){
				String heights = null;
				String textures = null;
				String monsters = null;
				String npcs = null;
				String buildings = null;
				String properties = null;
				if( propertieFile.equals( "Heights" ) )
					heights = readFile( propertieFile );
				if( propertieFile.equals( "Textures" ) )
					textures = readFile( propertieFile );
				if( propertieFile.equals( "Monsters" ) )
					monsters = readFile( propertieFile );
				if( propertieFile.equals( "NPCs" ) )
					npcs = readFile( propertieFile );
				if( propertieFile.equals( "Buildings" ) )
					buildings = readFile( propertieFile );
				if( propertieFile.equals( "Properties" ) )
					properties = readFile( propertieFile );
				
				this.mapFactory.createMap( heights, textures, monsters, npcs, buildings, properties );
			}
		}
		catch (URISyntaxException e) { e.printStackTrace();	}
	}
	
	private String readFile( File map ) {
		String chaine = "";
		try {
			BufferedReader buffer = new BufferedReader( new InputStreamReader( new FileInputStream( map ) ) );
			String line;
			while ( ( line = buffer.readLine() ) != null ){
				chaine += ( line + "\n" );
			}
			buffer.close();
		} 
		catch (IOException e) { e.printStackTrace(); }
		return chaine;
	}
	
	public static void main(String[] args) {
		MapLoader loader = new MapLoader();
		loader.load( "Forest" );
	}
	
}
